package com.touringapp.android.utils;

import com.commonsware.cwac.locpoll.LocationPoller;
import com.touringapp.android.service.LocationReceiver;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.os.SystemClock;
import android.widget.Toast;

public class LocationUtils {
	private static boolean started = false;
	
	public static synchronized void stop(final Context context) {
    	final AlarmManager mgr =(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        Intent i=new Intent(context, LocationPoller.class);
        
        i.putExtra(LocationPoller.EXTRA_INTENT,
                             new Intent(context, LocationReceiver.class));
        i.putExtra(LocationPoller.EXTRA_PROVIDER,
                             LocationManager.GPS_PROVIDER);
        
        PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
        mgr.cancel(pi);
        LocationReceiver.clear();
        started = false;
    }

	public static synchronized void start(final Context context, long period) {
		final AlarmManager mgr =(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        
        Intent i = new Intent(context, LocationPoller.class);
        
        i.putExtra(LocationPoller.EXTRA_INTENT,
                             new Intent(context, LocationReceiver.class));
        i.putExtra(LocationPoller.EXTRA_PROVIDER,
                             LocationManager.GPS_PROVIDER);
        PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
        mgr.cancel(pi);
        mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                                            SystemClock.elapsedRealtime(),
                                            period,
                                            pi);
        Toast.makeText(context,
                                "Location polling every " + period / 1000 + " seconds begun",
                                Toast.LENGTH_LONG).show();
        started = true;
    }
	
	public static boolean isStarted() {
		return started;
	}

}
